package com.example.zookeeperlock.highlock.impl;

import com.example.zookeeperlock.highlock.AbstractLock;
import org.I0Itec.zkclient.IZkDataListener;

import java.util.concurrent.CountDownLatch;

/**
 * @Author: zhangrongqing
 * @Date: 2020/9/1 11:27
 * 作用关心第一个锁，添加监听器，每次都循环获取
 */
public class SimpleZkLock extends AbstractLock {

    private CountDownLatch countDownLatch;

    @Override
    public Boolean tryLock() {
        System.out.println(Thread.currentThread().getName() + "正在获取锁");
        try {
            boolean exists = zkClient.exists(PATH);
            System.out.println(exists);
//        System.out.println(zkClient.getChildren(PATH));
            if (exists) {
                System.out.println("锁占用中。。。");
                return false;
            } else {
                System.out.println("获取锁。。。");
                zkClient.createEphemeral(PATH);
                return true;
            }
        } catch (RuntimeException e) {
//            System.out.println(e);
//            e.printStackTrace();
            return false;
        }

//        try {
//            zkClient.createEphemeral(PATH);
//            return true;
//        } catch (Exception e) {
//            System.out.println(e);
//            return false;
//        }

//        System.out.println(zkClient.getChildren(PATH));
//        return true;
    }

    @Override
    public void waitLock() {
        //监听器
        IZkDataListener iZkDataListener = new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {

            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                if (countDownLatch != null) {
                    countDownLatch.countDown();
                }
            }
        };

        zkClient.subscribeDataChanges(PATH, iZkDataListener);

        if (zkClient.exists(PATH)) {
            countDownLatch = new CountDownLatch(1);
            try {
                countDownLatch.await();
                System.out.println(Thread.currentThread().getName() + "等待锁...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        zkClient.unsubscribeDataChanges(PATH, iZkDataListener);

    }

    @Override
    public void releaseLock() {
        System.out.println(Thread.currentThread().getName() + "-释放锁成功");
        zkClient.delete(PATH);
        zkClient.close();
    }
}
